/**
 * Created by Mission on 16/10/10.
 */
$(function () {
    //获取页面间的url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    })(jQuery);
    var vote_id = $.getUrlParam('vote_id');             //当前投票id
    var from = $.getUrlParam('index');                  //来自哪个页面 对应home页面的三个tab
    var _token, _userId;
    var type = 0;                                         //是否来自分享
    var share_token = $.getUrlParam('token');               //获取分享过来的 token;
    var share_userId = $.getUrlParam('userId');             //获取分享过来的 用户id
    var canDelete = false;                            //只有id和localid相同 发起者才可以删除
    if (share_token == null || share_userId == null) {//0来自投票内部。1来自外部分享
        type = 0;
        _token = token;
        _userId = user_id;
    } else {
        type = 1;
        _userId = share_userId;
        _token = share_token;
    }
    var url = apiurl + "/vote/" + vote_id;
    var max;
    var option_ids;
    var current = 0;//目前选择了0项
    var yitou = 0;//已投人数
    var total = 0;//已投项数（考虑多选）
    var nametype = "";//1实名2匿名
    var chotype = 2;//1单选 多选
    var username, chotxt, title, desc, end_time, options, status;
    var pop_up = $('.pop-up');
    var colors = [
        "#E6CF73",
        "#73B6E6",
        "#E69173"];
    var btn_bg = [
        "#C5D556",
        "#C5D556",
        "#D6D6D6",
        "#D6D6D6"];
    //默认颜色
    var bgColor = 1, detail_bgColor = 1;

    var flash = false;//触发开关，防止多次调用事件
    var detail_id;//detail列表id
    var data = {
        user_id: _userId,
        token: _token,
    };
    $.ajax({
        beforeSend: function () {
            $(".loading").show();
        },
        url: url,
        type: "GET",
        data: data,
        success: function (d) {
            $(".loading").hide();
            if (d.code == 1) {
                if (d.msg == "202") {
                    //-----------------------------------------------
                    $('.token_iframe').show();
                }
            } else {
                console.log("/vote/vote_id:" + d);
                var createInfo = JSON.parse(d).data.createInfo;
                var data = JSON.parse(d).data.voteVo;

                yitou = parseInt(data.nums);//已投
                total = parseInt(data.total);

                chotype = data.is_multiselect;//多选
                if (chotype == 1) {
                    chotxt = "单选"
                } else {
                    chotxt = "可选" + chotype + "项";
                }
                title = data.vote_title;//标题
                desc = data.vote_desc;//说明
                end_time = new Date(data.end_time);//截止时间
                initDate(end_time);
                //发起人
                if (data.user_id == _userId) {
                    canDelete = true;
                    $("#more2").css("display", "block");
                } else {
                    canDelete = false;
                    $("#more2").css("display", "none");
                    $(".dialog-more").css("height", "17vh");

                }
                var user_avatar = "";
                var user_qyxBindId = "";
                if (createInfo.length > 0) {
                    for (var j = 0; j < createInfo.length; j++) {
                        if (createInfo[j].id == data.user_id) {
                            if (data.is_view == 1)//1不可见2可见
                            {
                                username = "匿名";
                                user_avatar = "";
                            } else {
                                username = createInfo[j].name;
                                user_avatar = createInfo[j].avatar;
                            }
                            user_qyxBindId = createInfo[j].qyxBindId;
                            bgColor = avatar_getColor(user_qyxBindId);
                        }
                    }
                }

                //1匿名2不匿名
                if (data.is_anonymous == 1) {
                    nametype = "实名投票";
                } else {
                    nametype = "匿名投票";
                }
                options = data.options;
                status = data.status;
                var status_txt;
                switch (status) {
                    case 0:
                        //status_txt = "发 布";
                        break;
                    case 1:
                        status_txt = "我要投票";
                        break;
                    case 2:
                        status_txt = "已结束";
                        break;
                    case 3:
                        status_txt = "已投票";
                        break;
                    default:
                        break;
                }
                //append
                var html = "";


                var reduced_name = avatar_name(username);
                var avatar_component = "<div class='round' style='background: " + bgColor + "'><span>" + reduced_name + "</span></div>";
                if (user_avatar.length > 0) {
                    user_avatar = avatar_getUrl(_userId, _token, user_avatar);
                    avatar_component += "<img src='" + user_avatar + "' class='round' hidden>";
                }

                //if (user_avatar == "") {
                    //如果无头像 改变底色、显示名字
                    //缩减名（后两位）
                var html = "<div class='head1'><div class='head1-ct'><div class='head1-img'>"+avatar_component+"</div><div class='head1-text'><div class='left-top'><div class='bold' id='name'>" +
                            username + "</div><div class='right-top'><img src='../img/right-top.png' class='img-style'><span id='see'>" +
                            nametype + "</span><span>/</span><span id='choice'>" +
                            chotxt + "</span></div></div><div class='left-bot'><div class='yitou'><span>已投:</span><span class='red' id='yitou'>" +
                            yitou + "</span></div><div class='right-bot'><img src='../img/right-bot.png' class='img-style'><span>截止</span><span id='date'>" +
                            mon_day_time + "</span></div></div></div></div></div><div class='head2'><div id='desc'  >" +
                            desc + "</div></div>";
                //} else {
                //    user_avatar = avatar_getUrl(_userId, _token, user_avatar);
                //    html = "<div class='head1'><div class='head1-ct'><div class='head1-img'><img src='" +
                //        user_avatar + "' class='round'/></div><div class='head1-text'><div class='left-top'><div class='bold' id='name'>" +
                //        username + "</div><div class='right-top'><img src='../img/right-top.png' class='img-style'><span id='see'>" +
                //        nametype + "</span><span>/</span><span id='choice'>" +
                //        chotxt + "</span></div></div><div class='left-bot'><div class='yitou'><span>已投:</span><span class='red' id='yitou'>" +
                //        yitou + "</span></div><div class='right-bot'><img src='../img/right-bot.png' class='img-style'><span>截止</span><span id='date'>" +
                //        mon_day_time + "</span></div></div></div></div></div><div class='head2'><div id='desc'  >" +
                //        desc + "</div></div>";
                //}
                $('.details-head').append(html);

                //标题
                var tit_html = "<div class='choose-title'><div class='title-icon'><img src='../img/hand.png' class='img-hand'></div><div class='title'>" + title + "</div></div>";
                $('.choose').prepend(tit_html);
                //底部按钮
                var bot_html = "<div class='btn-vote' id='voteBtn'><span class='vt-span'>" + status_txt + "</span></div>";
                $('.bottom').append(bot_html);
                var intro_html = "<div class='introduce-title' >投票详情</div>";
                $('.detail-introduce').append(intro_html);
                console.log("statuscolor:" + btn_bg[status]);
                $('.btn-vote').css("background-color", btn_bg[status]);
                //配置选项
                for (var i = 0; i < options.length; i++) {
                    var percent, process;
                    if (total == 0) {
                        percent = 0;
                    } else {
                        percent = parseFloat(((parseInt(options[i].option_num) * 100) / total).toFixed(1));
                    }
                    var option_pic = options[i].option_pic;
                    var item_html;
                    console.log("option_pic:" + option_pic);
                    if (!option_pic) {//为"1"时无图
                        item_html = "<div class='choose-item' id='" + options[i].option_id + "'><div class='checkbox' id='checkbox" + options[i].option_id + "'><img src='../img/check-off.png' class='img-check'/></div><div class='noimg_msg'><div class='msg-mid'><div class='mid-left'><span class='msg-top'>" + options[i].option_txt + "</span></div><div class='mid-right' style='padding-left: 0.7vh;padding-right: 0.7vh;text-align: center'> <span class='item-num'>" + options[i].option_num + "</span><span>票</span></div></div><div><div class='msg-bot' style='display:inline-block;width:80%;'><div class='process' id='process" + options[i].option_id + "' style='background:" + colors[i % colors.length] + "'></div></div><div class='right-bg' style='display:inline-block;background:" + colors[i % colors.length] + "'><span class='percent'>" + percent + "</span><span>%</span></div></div></div></div>"
                    } else {
                        item_html = "<div class='choose-item' id='" + options[i].option_id +
                            "'><div class='checkbox' id='checkbox" + options[i].option_id +
                            "'><img src='../img/check-off.png' class='img-check'/></div><div class='item-icon'><img src='" + option_pic +
                            "' class='img-icon'/></div><div class='item-msg'><div class='msg-top'>" + options[i].option_txt +
                            "</div><div class='msg-mid'><div class='mid-left'><span class='item-num'>" + options[i].option_num +
                            "</span><span>票</span></div><div class='mid-right'><div class='right-bg' style='background: " + colors[i % colors.length] +
                            ";'><span class='percent'>" + percent +
                            "</span><span>%</span></div></div></div><div class='msg-bot'><div class='process' id='process" + options[i].option_id +
                            "'style='background:" + colors[i % colors.length] + "'></div></div></div></div>";
                    }
                    $('.choose-content').append(item_html);


                    var mtop = parseFloat($("#" + options[i].option_id).css("height"));
                    var selfheight = parseFloat($("#checkbox" + options[i].option_id).css("height"));
                    console.log((mtop - selfheight) / 2);
                    $('#checkbox' + options[i].option_id).css("margin-top", (mtop - selfheight) / 2);
                    if (percent == 0) {
                        $("#process" + options[i].option_id).css("width", 0);
                    } else {
                        max = $("#" + options[i].option_id).find('.msg-bot').width();
                        $("#process" + options[i].option_id).css("width", parseInt(options[i].option_num) * max / total);
                    }
                    //如果已投票或者已过期那么隐藏选择框
                    if (status == 2 || status == 3) {
                        $(".img-check").css("display", "none");
                    }
                }

                showAvatar(".round");

                //具体已投情况
                detail_id = 0;
                detail_loading(detail_id);

                $(window).scroll(function () {
                    //当内容滚动到底部时加载新的内容 100当距离最底部100个像素时开始加载.
                    if ($(this).scrollTop() + $(document).height() + 100 >= $(document).height()) {

                        if (flash == true) {
                            flash = false;
                            detail_loading(detail_id);
                        }
                    }
                });

            }

        }

        ,
        error: function (d) {
            console.log(d);
        }
    });

    //获取detail已投列表
    function detail_loading(id) {
        var data = {
            vote_id: vote_id,
            user_id: _userId,
            token: _token,
            id: id
        };
        $.ajax({
            beforeSend: function () {
                $(".loading").show();

            },
            url: apiurl + "/vote/optionlist",
            type: "GET",
            data: data,
            success: function (d) {
                flash = true;
                $(".loading").hide();
                console.log(d);
                if (d.code == 1) {
                    if (d.msg == "202") {
                        //-----------------------------------------------
                        $('.token_iframe').show();
                    }
                } else {
                    var userInfos = JSON.parse(d).data.userInfos;
                    var data = JSON.parse(d).data.userVoteOptions;
                    if (data.length > 0) {
                        detail_id = data[parseInt(data.length - 1)].id;
                        for (var i = 0; i < data.length; i++) {
                            var update_time = new Date(data[i].create_timestamp);
                            initDate(update_time);
                            var detail_name = "";
                            var detail_avatar = "";//默认
                            var detail_qyxBindId = "";
                            var details_html = "";
                            //获取 头像、name
                            var detail_name_id = data[i].user_id;
                            if (userInfos.length > 0) {
                                for (var j = 0; j < userInfos.length; j++) {
                                    if (userInfos[j].id == detail_name_id) {
                                        if (nametype == "匿名投票") {
                                            detail_name = "匿名";
                                            detail_avatar = "";
                                        } else {
                                            detail_name = userInfos[j].name;
                                            detail_avatar = userInfos[j].avatar;

                                        }
                                        detail_qyxBindId = userInfos[j].qyxBindId;//用来取背景颜色
                                        //if (detail_avatar == "") {//无头像图片
                                            detail_bgColor = avatar_getColor(detail_qyxBindId);
                                            var reduced_name = avatar_name(detail_name);
                                            var avatar_component =  "<div class='detail-icon' style='background: " + detail_bgColor + "'>" +
                                                                        "<div class='detail_name'>" + reduced_name + "</div>" +
                                                                    "</div>";

                                            if (detail_avatar.length > 0){
                                                detail_avatar = avatar_getUrl(_userId, _token, detail_avatar);
                                                avatar_component += "<img src='" + detail_avatar + "'class='detail-icon' hidden>";
                                            }

                                            details_html = "<div class='introduce-detail' id='" + data[i].id + "'>" +
                                                                avatar_component +
                                                                "<div class='detail-right'>" +
                                                                    "<div class='detail-title'>" +
                                                                        "<div class='title-left'>" + detail_name + "</div>" +
                                                                        "<div class='title-right'><span>" + vote_detail_time + "</span></div>" +
                                                                    "</div>" +
                                                                    "<div class='choosed'><span>已投： “</span>" + data[i].vote_txt + "<span>”</span></div>" +
                                                                "</div>" +
                                                            "</div>";

                                        //} else {
                                        //    detail_avatar = avatar_getUrl(_userId, _token, detail_avatar);
                                        //    details_html = "<div class='introduce-detail' id='" + data[i].id + "'>" +
                                        //                        "<img src='" + detail_avatar + "'class='detail-icon'/>" +
                                        //                        "<div class='detail-right'>" +
                                        //                            "<div class='detail-title'>" +
                                        //                                "<div class='title-left'>" + detail_name + "</div>" +
                                        //                                "<div class='title-right'>" +
                                        //                                    "<span>" + vote_detail_time + "</span>" +
                                        //                                "</div>" +
                                        //                            "</div>" +
                                        //                            "<div class='choosed'><span>已投： “</span>" + data[i].vote_txt + "<span>”</span></div>" +
                                        //                        "</div>" +
                                        //                    "</div>";
                                        //}
                                        $('.detail-introduce').append(details_html);
                                    }

                                }
                                showAvatar(".detail-icon");
                            }

                        }
                    } else if (data.length < 10) {
                        //新加载的少于10条 脱绑
                        $(window).unbind('scroll');
                    }
                }
            },
            error: function (d) {
                flash = true;
                console.log(d);
            }
        });
    }

    $(document).on('click', '.img-icon', function () {
        $.watchBigPic($(this));
    });


    /**
     * 提示popupwindow－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    function pop_up_fn(obj, title) {

        if (obj.css("display") == "block") {

        } else {
            obj.text(title);
            obj.fadeIn();
            obj.fadeOut(3000);
        }
    }


    $("#detail_return").click(function () {
        if (type == 0) {
            location.href = "voteHome.html?index=" + from;
        } else {
            //－－－－－－－－－－－－－－－－－－－－－返回安卓平台
            var quitShare;
            quitShare = document.createElement('iframe');
            quitShare.style.display = 'none';
            document.documentElement.appendChild(quitShare);
            quitShare.src = "/quitShare_goBack";
        }

    });
    //更多
    $('#more').click(function () {
        $('#dbody').css('overflow', 'hidden');
        $('.dialogBg').show();

    });
    //分享
    $('#more1').click(function () {
        //--------------------跳到分享界面
        var attId = "";
        var team = localStorage.group_id;
        var content = "投票分享";
        var vote_title = title;
        var applicationId = vote_id;
        var applicationType = 2;
        var attSize = "";
        var hyperlink = "/vote/html/voteDetail.html?vote_id=" + vote_id + "";

        shareContent(attId, team, content, vote_title, applicationId, applicationType, attSize, hyperlink);

    });
    //删除
    $('#more2').click(function () {
        console.log(canDelete);
        if (canDelete == false) {
            $('.dialogBg').hide();
            $('#dbody').css('overflow', 'scroll');
            pop_up_fn(pop_up, "只有发起者才可删除");
        } else {
            $('.dialog-more').hide();
            $('.dialog').show();
        }
    });
    $(".btn-no").click(function () {
        $('.dialog-more').show();
        $('.dialog').hide();
    });
    $('.btn-yes').click(function () {
        $('.dialogBg').hide();
        $('.dialog-more').show();
        $('.dialog').hide();
        $('#dbody').css('overflow', 'scroll');
        //执行删除接口操作后返回上一个页面
        var deleteData = {
            vote_id: vote_id,
            user_id: _userId,
        };
        $.ajax({
            beforeSend: function () {
                $(".loading").show();
            },
            url: apiurl + "/vote/delete",
            data: deleteData,
            type: "POST",
            success: function (d) {
                console.log(d);
                $(".loading").hide();
                if (d.code == 1) {
                    pop_up_fn(pop_up, "删除出错啦");
                } else {
                    if (JSON.parse(d).code == 0) {
                        pop_up_fn(pop_up, "删除成功");
                        location.href = "voteHome.html?index=" + from;
                    }
                }
            },
            error: function (d) {
                console.log(d);
            }
        });
    });
    //取消
    $('#more3').click(function () {
        $('.dialogBg').hide();
        $('#dbody').css('overflow', 'scroll');
    });

    //勾选框
    $(document).on('click', '.checkbox', function () {
        if (chotype == 1) {
            //单选
            if ($(this).children("img").attr("src") == "../img/check-off.png") {
                $(".checkbox").each(function () {
                    if ($(this).children("img").attr("src") == "../img/check-on.png") {
                        var sub = parseInt($(this).parent().find('.item-num').text()) - 1;
                        $(this).parent().find('.item-num').text(sub);
                    }
                });
                $('.checkbox').children("img").attr("src", "../img/check-off.png");
                $(this).children("img").attr("src", "../img/check-on.png");
                var add = parseInt($(this).parent().find('.item-num').text()) + 1;
                $(this).parent().find('.item-num').text(add);
            }
            //逐个修改显示
            $(".checkbox").each(function () {
                var num = parseInt($(this).parent().find('.item-num').text());
                max = $(this).parent().find('.msg-bot').width();
                $(this).parent().find('.percent').text(parseInt((num * 100 / (total + 1) )));
                $(this).parent().find('.process').css("width", parseInt(num * max / (total + 1)));
            });


        } else {
            //多选
            if ($(this).children("img").attr("src") == "../img/check-off.png") {
                if (current < chotype) {
                    $(this).children("img").attr("src", "../img/check-on.png");
                    var add = parseInt($(this).parent().find('.item-num').text()) + 1;
                    $(this).parent().find('.item-num').text(add);
                    total = total + 1;
                    current++;
                }

            } else {
                $(this).children("img").attr("src", "../img/check-off.png");
                var sub = parseInt($(this).parent().find('.item-num').text()) - 1;
                $(this).parent().find('.item-num').text(sub);
                total = total - 1;
                current--;
            }
            $(".checkbox").each(function () {
                max = $(this).parent().find('.msg-bot').width();
                if (total == 0) {
                    $(this).parent().find('.percent').text("0");
                    $(this).parent().find('.process').css("width", 0);
                } else {
                    var num = parseInt($(this).parent().find('.item-num').text());
                    // $(this).parent().find('.percent').text(parseFloat((num * 100.0 / total).toFixed(1)));
                    $(this).parent().find('.percent').text(parseInt((num * 100 / total)));
                    $(this).parent().find('.process').css("width", parseInt(num * max / total));
                }
            });
        }

    });
    $(document).on('click', '#voteBtn', function () {
        switch (status) {
            case 0:
                break;
            case 1://投票

                $(".checkbox").each(function () {
                    if ($(this).children("img").attr("src") == "../img/check-on.png") {
                        if (option_ids != null) {
                            option_ids = option_ids + $(this).parent().attr("id") + ";";
                        }
                        else {
                            option_ids = $(this).parent().attr("id") + ";";
                        }
                    }
                });
                if (option_ids == null) {
                    pop_up_fn(pop_up, "请先选择您支持的投票项");
                } else {

                    var data = {
                        vote_id: vote_id,
                        user_id: _userId,
                        option_id: option_ids,
                    };
                    console.log(data);
                    $.ajax({
                        url: apiurl + "/vote/vote",
                        type: "POST",
                        data: data,
                        success: function (d) {
                            console.log(d);
                            if (d.code == 1) {
                            } else {
                                if (JSON.parse(d).code == 0) {
                                    pop_up_fn(pop_up, "投票成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 800);
                                }
                            }
                        }
                    });
                }
                break;
            case 2:
                pop_up_fn(pop_up, "已过期");
                break;
            case 3:
                pop_up_fn(pop_up, "您已投票，无法重复投票");
                break;
            default:
                break;
        }
    });

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }
});